<?php


namespace App\Http\Controllers\Admin;

use App\Exceptions\ServiceException;
use App\Http\Controllers\Controller;
use App\Jobs\PushNotification;
use App\Jobs\SendActInfo;
use App\Models\Game\ActEventList;
use App\Models\Game\Server;
use App\Utils\InitUtils;
use App\Utils\MyLog;
use App\Utils\ResponseUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class ActEditController extends  Controller
{

    private Request $request;
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public  function paginate(){

        $page = request()->get('page');
        $limit= request()->get('limit');
        $gameArea = request()->get('gameArea');
        $gameAreas = explode(',', $gameArea);
        $payTimeBegin = strtotime(request()->get('createDateBegin'));
        $payTimeEnd = strtotime(request()->get('createDateEnd'));

        if (!$payTimeBegin) {
            return ResponseUtil::error("开始时间不能为空");
        }
        if (!$payTimeEnd) {
            return ResponseUtil::error("结束时间不能为空");
        }
        $roleid =request()->get('roleid');

        $roleids = explode(',', $roleid);
        $result=[];
        foreach ($gameAreas as $area){
        $query = "SELECT roleId, ROUND(SUM(rmbAmount)) AS totalAmount , LEFT(memId, 1) AS severarea
                  FROM log_role_iap_buy
                  WHERE processTime BETWEEN ? AND ?  ";
        $bindings = [$payTimeBegin, $payTimeEnd];



            if (!empty($roleid)) {
                MyLog::info("用户ID" . json_encode($roleid));

                $query .= " AND roleId IN (" . implode(',', $roleids) . ")";
                $bindings = array_merge($bindings, $gameAreas);
            }

        $query .= " GROUP BY roleId,severarea ";

            if ($area) {
               $queryResult = DB::connection('log_' . $area)->select($query, $bindings);

               $result = array_merge($result, $queryResult);
            }
        }



        $res = [];
        $count = count($result);
        $res['count']=$count;
        $res['code']=0;
        $data =InitUtils::initPage($result,$page,$limit);
        $res['data']=$data;

        return  $res;

    }



    public function send(){
        ini_set('max_execution_time', 120);
        $gameArea = request()->get('gameArea');
        $gameAreas = explode(',', $gameArea);
        $payTimeBegin = strtotime(request()->get('createDateBegin'));
        $payTimeEnd = strtotime(request()->get('createDateEnd'));
        $acttype = request()->get('acttype');
        $actid= request()->get('actid');
        $roleid =request()->get('roleid');
        MyLog::info('请求的角色id'.json_encode($roleid));
        if (!$payTimeBegin) {
            return ResponseUtil::error("开始时间不能为空");
        }
        if (!$payTimeEnd) {
            return ResponseUtil::error("结束时间不能为空");
        }
        if($roleid){
            $result=[];
            if($gameAreas){
                foreach ($gameAreas as $area) {
                    $query = "SELECT roleId, ROUND(SUM(rmbAmount)) AS totalAmount, LEFT(memId, 1) AS severarea
                      FROM log_role_iap_buy
                      WHERE processTime BETWEEN ? AND ? ";

                    $bindings = [$payTimeBegin, $payTimeEnd];


                    // 添加 roleId 的判断条件
                    $query .= " AND roleId = ? ";
                    $bindings[] = $roleid;

                    $query .= " GROUP BY roleId, severarea ";

                    if ($area) {
                        $queryResult = DB::connection('log_' . $area)->select($query, $bindings);
                        $result = array_merge($result, $queryResult);
                    }
                }
                MyLog::info('查看组装角色ID信息'.json_encode($result));
                foreach ($result as $list)
                {
                    $gamearea = data_get($list,'severarea');
                    $money = data_get($list,'totalAmount');
                    $roleId= data_get($list,'roleId');
                    $model = Server::query()->where('server_id',$gameArea)->first(); //->toArray();
                    MyLog::info('服务器地址'.json_encode($model));
                    //构造消息体
                    $assembledData = [
                        "RoleId" => (int)$roleId,
                        "ActType" => (int)$acttype,
                        "ActId" => (int)$actid,
                        "ActData" => [
                            "TlAccu" => [
                                "AccuRcYmb" => (int)$money
                            ]
                        ]
                    ];
                    //获取当前服务器的后端推送地址
                    $pushUrl = $model->push_url;
                    $pushUrl = rtrim($pushUrl, '/') . '/'; // 移除末尾的斜杠并添加一个斜杠
                    $apiEndpoint = 'Api/Act/SetActInfo';
                    $url = $pushUrl . $apiEndpoint;
                    dispatch(new PushNotification($assembledData, $url,$gameArea))->onQueue('push');
                    //$this->sendbady($assembledData,$url);
                    usleep(20000); // 等待 100 毫秒
                }
            }

        }else{


        $result=[];
        if($gameAreas){
            foreach ($gameAreas as $area){
                $query = "SELECT roleId, ROUND(SUM(rmbAmount)) AS totalAmount , LEFT(memId, 1) AS severarea
                  FROM log_role_iap_buy
                  WHERE processTime BETWEEN ? AND ?  ";
                $bindings = [$payTimeBegin, $payTimeEnd];
                if ($gameArea) {
                    $query .= " AND LEFT(memId, 1) = ?";
                    $bindings[] = $area;
                }
                $query .= " GROUP BY roleId,severarea ";

                if ($area) {
                    $queryResult = DB::connection('log_' . $area)->select($query, $bindings);
                    $result = array_merge($result, $queryResult);
                }
            }
            foreach ($result as $list)
            {
                $gamearea = data_get($list,'severarea');
                $money = data_get($list,'totalAmount');
                $roleId= data_get($list,'roleId');
                $model = Server::query()->where('server_id',$gamearea)->first(); //->toArray();

                //构造消息体
                $assembledData = [
                    "RoleId" => (int)$roleId,
                    "ActType" => (int)$acttype,
                    "ActId" => (int)$actid,
                    "ActData" => [
                        "TlAccu" => [
                            "AccuRcYmb" => (int)$money
                        ]
                    ]
                ];
                //获取当前服务器的后端推送地址
                $pushUrl = $model->push_url;
                $pushUrl = rtrim($pushUrl, '/') . '/'; // 移除末尾的斜杠并添加一个斜杠
                $apiEndpoint = 'Api/Act/SetActInfo';
                $url = $pushUrl . $apiEndpoint;
                dispatch(new PushNotification($assembledData, $url,$gamearea))->onQueue('push');
                //$this->sendbady($assembledData,$url);
                usleep(20000); // 等待 100 毫秒
            }
        }
        }
    }


         public  function    operatepaginate(){
             $acttype = request()->get('acttype');
             $actid= request()->get('actid');

             $roleid = request()->get('roleid');
             $roleids = explode(',', $roleid);
             $page = request()->get('page');
             $limit= request()->get('limit');
             $gameArea = request()->get('gameArea');
             $gameAreas = explode(',', $gameArea);
             $gameAreaPlaceholders = array_fill(0, count($gameAreas), '?');

             $payTimeBegin = request()->get('createDateBegin');
             $payTimeEnd = request()->get('createDateEnd');

             if (!$payTimeBegin) {
                 return ResponseUtil::error("开始时间不能为空");
             }
             if (!$payTimeEnd) {
                 return ResponseUtil::error("结束时间不能为空");
             }
             $query = "SELECT RoleId, ActType , ActId,status ,server_id ,created_at,AccuRcYmb,pushUrl FROM acctevent_list WHERE created_at BETWEEN ? AND ?";

             $bindings = [$payTimeBegin, $payTimeEnd];

             if ($actid) {
                 $query .= " AND  ActId = ?";
                 $bindings[] = $actid;
             }
             if ($acttype) {
                 $query .= " AND ActType = ?";
                 $bindings[] = $acttype;
             }

             if (!empty($gameArea)) {

                 $query .= " AND server_id IN (" . implode(',', $gameAreaPlaceholders) . ")";
                 $bindings = array_merge($bindings, $gameAreas);
             }
             $query .= " ORDER BY created_at DESC"; // 添加倒序排序语句

             $result = DB::select($query, $bindings);


             $res = [];
             $count = count($result);
             $res['count']=$count;
             $res['code']=0;
             $data =InitUtils::initPage($result,$page,$limit);
             $res['data']=$data;

             return  $res;

         }



}
